package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Integral;
import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.mapper.IntegralMapper;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.service.ISignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SignServiceImpl implements ISignService {
    @Autowired
    private SignMapper signMapper;
    @Autowired
    private IntegralMapper integralMapper;

    @Override
    public Sign selectBuUserId(Long userId) {

        return signMapper.selectBuUserId(userId);
    }

    @Override
    public void save(Sign sign) {
        //先查出上一次签到情况
        Sign sign1 = signMapper.selectLastSign(sign.getUser().getId());
        Integral integral=integralMapper.selectByUserId(sign.getUser().getId());
        Integral integral1 = new Integral();
        //第一次签到
        if (sign1 == null) {
            //签到表
            sign.setConstant(1);
            sign.setTotal(1);
            signMapper.insert(sign);
            //积分表
            integral1.setIntegral(0);
            integral1.setUser(sign.getUser());
            integralMapper.insert(integral1);
        } else {
            //获得上一次的时间
            Date d1 = sign1.getCreateTime();
            //获得现在签到的时间
            Date d2=sign.getCreateTime();
            long diff = d2.getTime() - d1.getTime();//这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            if (days==0){
                throw new RuntimeException("今天已经签过了");
            }
            //断签
            if (days>1){
                sign.setConstant(1);
            }else {
                sign.setConstant(sign1.getConstant() + 1);
            }
            sign.setTotal(sign1.getTotal() + 1);
            signMapper.updateByUserId(sign);

            //签到7的倍数可以加积分
            if ((sign1.getConstant() + 1)%7==0){
                    integralMapper.updateByUserId(sign.getUser().getId());
            }
        }
    }
}
